package com.torfox.modules.livelog;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;

@Slf4j
@Controller
public class LiveServlet extends WebSocketHandler implements ApplicationContextAware
{

	private Server server;

	private ApplicationContext context;

	private LiveLogConnectionFactory connectionFactory;

	@PostConstruct
	public void init() throws ServletException
	{
		try
		{
			server = new Server(9091);
			// Register ChatWebSocketHandler in the Jetty server instance.
			this.setHandler(new DefaultHandler());
			server.setHandler(this);
			// Start the Jetty server.
			server.start();
		}
		catch (final Throwable e)
		{
			log.error("Socket error", e);
		}
	}

	@Override
	public void destroy()
	{
		try
        {
			if( server != null && server.isRunning())
            {
	            server.stop();
            }
        }
        catch (final Exception e)
        {
        	log.error( "Error stopping jetty server", e);
        }
	}

	@Override
	public WebSocket doWebSocketConnect(final HttpServletRequest request, final String protocol)
	{
		return connectionFactory.createConnection(request, protocol);
	}

	@Override
	public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException
	{
		context = applicationContext;
		connectionFactory = context.getBean(LiveLogConnectionFactory.class);
	}

	@Override
	public boolean checkOrigin(final HttpServletRequest request, final String origin)
	{
		return true;
	}
}
